package com.ithema.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ithema.reggie.common.R;
import com.ithema.reggie.entity.User;
import com.ithema.reggie.exception.BusinessException;
import com.ithema.reggie.mapper.UserMapper;
import com.ithema.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public R<User> login(String phone, String requestCode, String sessionCode) {
        //1.判断用户输入的验证码是否为空
        if (StrUtil.isBlank(requestCode)) {
            throw new BusinessException("验证码不能为空~");
        }

        //2.判断session中是否存在验证码
        if (StrUtil.isBlank(sessionCode)) {
            throw new BusinessException("请先获取验证码~");
        }

        //3.判断俩验证码是否一致
        if (!StrUtil.equals(requestCode,sessionCode)) {
            throw new BusinessException("请输入正确的验证码~");
        }

        //4.若一致,再通过手机号去数据库查询用户
        User user = userMapper.findByPhone(phone);

        //5.若用户不存在,新增用户
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);

            userMapper.save(user);
        }

        return R.success(user);
    }
}
